package com.like.banzipao.server.util

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.like.banzipao.server.model.Player
import com.like.banzipao.server.model.Poker
import com.like.banzipao.server.model.Suit
import com.like.banzipao.server.model.pokerComparator
import org.ktorm.jackson.KtormModule

val objectMapper = ObjectMapper().apply {
    registerModule(KtormModule())
    registerKotlinModule()// 支持 kotlin，比如 data class 的序列化
}

/**
 * 发牌
 * 创建52张牌，然后洗牌，按照庄家开始逆时针排序分给4个玩家，然后再按照新扑克那样排好序
 */
fun dealPokers(dealerUserId: Int, players: Array<Player>): List<Poker> {
    // 创建52张牌
    val pokers = mutableListOf<Poker>()
    var id = 0
    for (i in 0..3) {
        for (j in 3..15) {
            pokers.add(Poker(id++, j, Suit.values()[i]))
        }
    }
    val dealerIndex = players.indexOfFirst { it.user.id == dealerUserId }
    return pokers.apply {
        forEachIndexed { index, poker ->
            when (index) {
                in 0..12 -> poker.holderUserId = dealerUserId
                in 13..25 -> poker.holderUserId = players[(dealerIndex + 1) % 4].user.id
                in 26..38 -> poker.holderUserId = players[(dealerIndex + 2) % 4].user.id
                in 39..51 -> poker.holderUserId = players[(dealerIndex + 3) % 4].user.id
            }
        }
    }.sortedWith(pokerComparator)
}
